package com.tinem.platform.module.starter.web.filter;

import cn.hutool.core.util.StrUtil;
import com.tinem.platform.module.pojo.co.GatewayHeadName;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className GatewayFilter
 * @description TODO
 * @site 
 * @company 
 * @create 2020-07-04 10:09
 */
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {

    }
    @Override
    public void destroy() {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        if(StrUtil.isEmpty(request.getHeader(HttpHeaders.ORIGIN))){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN,request.getHeader(HttpHeaders.ORIGIN));
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, GatewayHeadName.X_PLATFORM_RES_CODE+","+ GatewayHeadName.X_PLATFORM_RES_MESSAGE+","+GatewayHeadName.X_PLATFORM_RES_SUCCESS+","+GatewayHeadName.X_PLATFORM_RES_CODE);
        response.setHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD,StrUtil.format("{},{}", HttpMethod.GET.name(), HttpMethod.POST.name()));
        filterChain.doFilter(request,response);
    }
}